package com.zjcode.cdcer.service.impl;

import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.utils.StringUtils;
import com.zjcode.cdcer.mapper.CerDetaildataImportInfoMapper;
import com.zjcode.cdcer.mapper.CerDetaildataImportOfficeInfoMapper;
import com.zjcode.cdcer.mapper.CerSysteminitImportOfficialInfoMapper;
import com.zjcode.cdcer.mapper.SysOrgMapper;
import com.zjcode.cdcer.mapper.TkmGastroscopeDiagnosisInfoMapper;
import com.zjcode.cdcer.mapper.TkmSysUserMapper;
import com.zjcode.cdcer.mapper.TkmSysteminitImportInfoMapper;
import com.zjcode.cdcer.mapper.ZjcodeSysRegionMapper;
import com.zjcode.cdcer.model.SysOrg;
import com.zjcode.cdcer.model.TkmSysEx;
import com.zjcode.cdcer.model.TkmSysUser;
import com.zjcode.cdcer.model.TkmUserOrgAndRegions;
import com.zjcode.cdcer.model.ZjcodeSysRegion;
import com.zjcode.cdcer.service.SysUserService;
import com.zjcode.cdcer.service.TkmSysExService;
import com.zjcode.cdcer.service.TkmSysUserService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @ClassName:TkmSysUserServiceImpl
 * @功能：
 * @author：wlei
 * @日期：2022/7/28-16:16
 **/
@Service
public class TkmSysUserServiceImpl implements TkmSysUserService, BaseService {

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    @Autowired
    private TkmSysUserMapper sysUserMapper;
    @Autowired
    private TkmSysteminitImportInfoMapper systeminitImportInfoMapper;
    @Autowired
    private CerSysteminitImportOfficialInfoMapper systeminitImportOfficialInfoMapper;
    @Autowired
    private CerDetaildataImportInfoMapper detaildataImportInfoMapper;
    @Autowired
    private CerDetaildataImportOfficeInfoMapper detaildataImportOfficeInfoMapper;
    @Autowired
    private TkmGastroscopeDiagnosisInfoMapper gastroscopeDiagnosisInfoMapper;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private ZjcodeSysRegionMapper sysRegionMapper;
    @Autowired
    private TkmSysExService tkmSysExService;

    @Override
    public int updateUserPassword(String userId, String password) {

        password = Optional
            .ofNullable(password)
            .orElse("123456");

        // 更新系统扩展信息表中的数据
        TkmSysEx sysEx = tkmSysExService.findBySourceId(userId);
        if (sysEx != null) {
            // 删除旧数据
            tkmSysExService.deleteBySourceId(userId);
            sysEx.setSourceId(userId);
            sysEx.setBillNo(password);
            // 创建新数据
            tkmSysExService.insert(sysEx);
        } else {
            sysEx = new TkmSysEx();
            sysEx.setId(get32UUID());
            sysEx.setSourceId(userId);
            sysEx.setBillNo(password);
            sysEx.setCreateDatetime(new Date(System.currentTimeMillis()));
            // 创建新数据
            tkmSysExService.insert(sysEx);
        }

        // 更新用户表中的数据
        password = encoder.encode(password);
        return sysUserMapper.updatePasswordById(password, Long.parseLong(userId));
    }

    @Override
    public int updateRecordExtflag(String userId) {
        String extFlag = sysUserService.findUserExtFlag(userId);
        // 修改初始数据上报中的数据
        int count1 = systeminitImportInfoMapper.updateExtFlagByCreateBy(extFlag, userId);
        // 修改初始数据正式库中的数据
        int count2 = systeminitImportOfficialInfoMapper.updateExtFlagByCreateBy(extFlag, userId);
        // 修改详情数据上报中的数据
        int count3 = detaildataImportInfoMapper.updateExtFlagByCreateBy(extFlag, userId);
        // 修改详情数据上报正式库中的数据
        int count4 = detaildataImportOfficeInfoMapper.updateExtFlagByCreateBy(extFlag, userId);
        // 修改胃镜诊疗总量信息表中的数据
        int count5 = gastroscopeDiagnosisInfoMapper.updateExtFlagByCreateBy(extFlag, userId);
        return count1 + count2 + count3 + count4 + count5;
    }

    @Override
    public TkmUserOrgAndRegions findUserRegionsAndOrg(String userId) {
        List<ZjcodeSysRegion> regions = new ArrayList<>();
        SysOrg sysOrg = sysOrgMapper.findByUserId(userId);
        String regionAncestors = sysOrg.getRegionAncestors();
        // 筛查机构的机构编码
        String orgCode = "";
        if (!StringUtils.isEmpty(regionAncestors)) {
            String[] split = regionAncestors.split(",");
            regions.addAll(sysRegionMapper.selectAllByCodeIn(Arrays.asList(split)));
        } else {
            // 医疗机构的regionAncestors可能为null,此时将用该机构的机构编码代替regions
            orgCode = sysOrg.getOrgCode();

            String provinceName = sysOrg.getProvinceName();
            String provinceCode = sysOrg.getProvinceCode();

            ZjcodeSysRegion province = getSysRegionBy(sysOrg.getProvinceCode(),
                                                      sysOrg.getProvinceName(),
                                                      "province");
            ZjcodeSysRegion city = getSysRegionBy(sysOrg.getCityCode(),
                                                  sysOrg.getCityName(),
                                                  "city");
            ZjcodeSysRegion region = getSysRegionBy(sysOrg.getRegionCode(),
                                                    sysOrg.getRegionName(),
                                                    "district");

            regions.add(province);
            regions.add(city);
            regions.add(region);
        }

        TkmUserOrgAndRegions result = new TkmUserOrgAndRegions();
        result.setSysOrg(sysOrg);
        result.setRegions(regions);
        result.setOrgCode(orgCode);
        return result;
    }

    @Override
    public TkmSysUser selectByUserId(long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    private ZjcodeSysRegion getSysRegionBy(String code, String name, String regionType) {
        ZjcodeSysRegion sysRegion = new ZjcodeSysRegion();
        sysRegion.setRegionName(name);
        sysRegion.setRegionCode(code);
        sysRegion.setRegionType(regionType);
        return sysRegion;
    }
}
